<template>
  <span class="header-search">
    <span @click="toggleSearch">
      <Icon type="ios-search-strong" class="icon"></Icon>
    </span>
    <div class="search-bar" :class="isShow ? 'show' : ''">
      <Select ref="select" :placeholder="placeholder" @on-change="handleChange">
        <Input ref="input" slot="input" v-model="currentValue" :placeholder="placeholder" @on-blur="handleBlur" @on-enter="handleEnter"></Input>
        <Option v-for="(item, index) in dataSource" :value="item" :key="index">{{ item }}</Option>
      </Select>
    </div>
  </span>
</template>
<script>
export default {
  name: 'HeaderSearch',
  data() {
    return {
      isShow: false,
      currentValue: this.value,
      toggleBySelect: false
    }
  },
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    placeholder: {
      type: String
    },
    dataSource: {
      type: Array
    }
  },
  methods: {
    handleChange(val) {
      this.toggleBySelect = true
      this.currentValue = val
      this.$refs.select.model = val
      this.$refs.input.focus()
      this.$emit('onSearch', val)
    },
    handleBlur() {
      setTimeout(() => {
        if (this.toggleBySelect) {
          this.toggleBySelect = false
        } else {
          this.toggleSearch()
        }
      }, 200)
    },
    toggleSearch() {
      this.isShow = !this.isShow
      if (this.isShow) {
        this.$refs.input.focus()
      }
    },
    handleEnter() {
      this.$emit('onSearch', this.currentValue)
      this.$emit('onPressEnter', this.currentValue)
    }
  },
  watch: {
    currentValue(newVal, oldVal) {
      this.$emit('onChange', newVal)
    }
  }
}
</script>
<style scoped>
.header-search .icon {
  font-size: 18px;
  vertical-align: middle;
  cursor: pointer;
}

.header-search .search-bar {
  width: 0;
  transition: width 0.3s, margin-left 0.3s;
  overflow: hidden;
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}

.header-search .search-bar.show {
  width: 210px;
}
</style>
<style>
.header-search .ivu-input {
  border: none;
  border-radius: 0;
  border-bottom: 1px solid #d9d9d9;
}

.header-search .ivu-auto-complete {
  transition: width 0.3s, margin-left 0.3s;
  overflow: hidden;
}

.header-search .ivu-select-selection,
.header-search .ivu-select-visible .ivu-select-selection {
  border: none;
}
</style>
